<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="120px"
    >
      <el-form-item label="优惠券名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入优惠券名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="优惠券图标" prop="icon">
				<el-input v-model="queryParams.icon" placeholder="请输入优惠券图标" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item> -->
      <el-form-item label="使用范围" prop="range">
        <el-select v-model="queryParams.range" placeholder="请选择使用范围">
          <el-option
            v-for="item in [
              { value: '1', label: '全家政业务' },
              { value: '2', label: '指定家政服务' },
            ]"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="指定商品ID" prop="subId">
				<el-input v-model="queryParams.subId" placeholder="请输入指定商品ID" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item> -->
      <el-form-item label="发放群体" prop="colony">
        <el-select v-model="queryParams.colony" placeholder="请选择发放群体">
          <el-option
            v-for="item in [
              { value: '1', label: '新用户' },
              { value: '2', label: '全部用户' },
              { value: '3', label: '指定用户' },
            ]"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否禁用" prop="isDis">
        <el-select v-model="queryParams.isDis" placeholder="请选择">
          <el-option
            v-for="item in [
              { value: '1', label: '禁用' },
              { value: '0', label: '启用' },
            ]"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:coupon:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:coupon:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:coupon:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:coupon:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="couponList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="优惠券名称" align="center" prop="name" />
      <el-table-column label="优惠券图标" align="center">
        <template slot-scope="scope">
          <image-preview
            :src="scope.row.icon"
            :width="50"
            :height="50"
          />
        </template>
      </el-table-column>
      <el-table-column label="使用范围" align="center">
        <template slot-scope="scope">
          <el-tag
            type="warning"
            v-if="scope.row.range == 1 && scope.row.type == 1"
            >全家政业务</el-tag
          >
          <el-tag
            type="warning"
            v-if="scope.row.range == 1 && scope.row.type == 2"
            >全团购业务</el-tag
          >
          <el-tag
            type="success"
            v-if="scope.row.range == 2 && scope.row.type == 1"
            >指定家政服务</el-tag
          >
          <el-tag
            type="success"
            v-if="scope.row.range == 2 && scope.row.type == 2"
            >指定团购服务</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="使用类型" align="center">
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.useType == 1">平台券</el-tag>
          <el-tag type="" v-if="scope.row.useType == 2">补偿券</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="指定商品ID" align="center" prop="subId" /> -->
      <el-table-column label="优惠券类型" align="center">
        <template slot-scope="scope">
          <el-tag type="warning" v-if="scope.row.conpType == 1">满减券</el-tag>
          <el-tag type="success" v-if="scope.row.conpType == 2">折扣券</el-tag>
          <el-tag type="error" v-if="scope.row.conpType == 3">体验券</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优惠券数量" align="center" prop="conpNum" />
      <el-table-column label="已领取数量" align="center" prop="surplus" />
      <el-table-column label="已使用数量" align="center" prop="useNum" />
      <!-- <el-table-column label="优惠券描述" align="center" prop="conpText" /> -->
      <el-table-column label="有效期" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.lifespanType == 1">
            <div>
              开始时间:{{
                scope.row.lifespanTextObject.startTime.substring(0, 10)
              }}
            </div>
            <div>
              结束时间:{{
                scope.row.lifespanTextObject.endTime.substring(0, 10)
              }}
            </div>
          </div>
          <div v-if="scope.row.lifespanType == 2">
            <div>{{ scope.row.lifespanTextObject.lifespan }}天</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="发放群体" align="center">
        <template slot-scope="scope">
          <el-tag type="warning" v-if="scope.row.colony == 1">新用户</el-tag>
          <el-tag type="primary" v-if="scope.row.colony == 2">全部用户</el-tag>
          <el-tag type="error" v-if="scope.row.colony == 3">指定用户</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="是否禁用" align="center" prop="isDis">
				<template slot-scope="scope">
					<el-tag type="info" v-if="scope.row.isDis == 1">已禁用</el-tag>
					<el-tag type="success" v-if="scope.row.isDis == 0">已启用</el-tag>
				</template>
			</el-table-column> -->
      <el-table-column label="是否启用" align="center" prop="isDis">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isDis"
            active-color="#13ce66"
            :active-value="0"
            :inactive-value="1"
            inactive-color="#999"
            @change="changeisDis(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="是否为活动" align="center" prop="isActivity">
        <template slot-scope="scope">
          <span v-if="scope.row.isActivity == 1">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:coupon:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:coupon:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠券对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="优惠券名称" prop="name" required>
          <el-input v-model="form.name" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="优惠券图标" prop="icon" required>
          <image-upload v-model="form.icon" :limit="1" />
        </el-form-item>
        <el-form-item label="所属业务" prop="type" required>
          <el-radio-group v-model="form.type">
            <el-radio :label="1">家政</el-radio>
            <el-radio :label="2">团购</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="使用范围"
          prop="range"
          required
          v-if="form.type == 1"
        >
          <el-radio-group v-model="form.range">
            <el-radio :label="1">全家政业务</el-radio>
            <el-radio :label="2">指定家政服务</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="使用范围" prop="range" required v-else>
          <el-radio-group v-model="form.range">
            <el-radio :label="1">全团购业务</el-radio>
            <el-radio :label="2">指定团购服务</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="指定商品ID"
          prop="subId"
          required
          v-if="form.range == 2 && form.type == 1"
        >
          <el-select
            v-model="form.subId"
            multiple
            placeholder="请选择商品"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in productList"
              :key="item.id"
              :label="item.title"
              :value="String(item.id)"
            >
              <span>{{ item.id }}</span>
              <img
                class="ml10"
                style="width: 20px; height: 20px; vertical-align: middle"
                :src="api_host + item.icon"
                alt=""
              />
              <span class="ml10">{{ item.title }}</span>
              <span class="ml10 orange">￥{{ item.price }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="指定商品"
          prop="subId"
          required
          v-if="form.range == 2 && form.type == 2"
        >
          <el-select
            v-model="form.subId"
            multiple
            placeholder="请选择商品"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in tuangouProList"
              :key="item.id"
              :label="item.goodName"
              :value="String(item.id)"
            >
              <span>{{ item.id }}</span>
              <img
                class="ml10"
                style="width: 20px; height: 20px; vertical-align: middle"
                :src="api_host + item.icon"
                alt=""
              />
              <span class="ml10">{{ item.goodName }}</span>
              <span class="ml10 orange">￥{{ item.salePrice }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="使用类型" prop="useType" required>
          <el-select
            v-model="form.useType"
            placeholder="请选择优惠券使用类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in [
                { value: 1, label: '平台券' },
                { value: 2, label: '补偿券' },
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券类型" prop="conpType" required>
          <el-select
            v-model="form.conpType"
            placeholder="请选择优惠券类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in [
                { value: 1, label: '满减券' },
                { value: 2, label: '折扣券' },
                { value: 3, label: '体验券' },
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券设置" v-if="form.conpType == 1">
          <span>消费券满</span>
          <el-input
            v-model="form.conpTextObject.fullAmount"
            type="number"
            placeholder=""
            style="width: 100px"
          />
          <span>元 立减</span>
          <el-input
            v-model="form.conpTextObject.deductionAmount"
            type="number"
            placeholder=""
            style="width: 100px"
          />
          <span>元</span>
        </el-form-item>
        <el-form-item label="优惠券设置" v-if="form.conpType == 2">
          <span>折扣</span>
          <el-input
            v-model="form.conpTextObject.discount"
            type="number"
            placeholder=""
            style="width: 100px"
          />
          <span>最大抵扣金额</span>
          <el-input
            v-model="form.conpTextObject.maxReduction"
            type="number"
            placeholder=""
            style="width: 100px"
          />
        </el-form-item>

        <el-form-item label="有效期设置" prop="lifespanType" required>
          <el-radio-group v-model="form.lifespanType">
            <el-radio :label="1">固定时间</el-radio>
            <el-radio :label="2">相对时间</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row v-if="form.lifespanType == 1">
          <el-form-item label="开始时间" prop="startTime" required>
            <el-date-picker
              v-model="form.startTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
              type="date"
              placeholder="选择开始时间"
              @change="changeDate"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime" required>
            <el-date-picker
              v-model="form.endTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
              type="date"
              placeholder="选择结束时间"
              @change="changeDate"
            >
            </el-date-picker>
          </el-form-item>
        </el-row>
        <el-row v-if="form.lifespanType == 2">
          <el-form-item
            label="有效期天数"
            prop="lifespanTextObject.lifespan"
            required
          >
            <el-input
              v-model="form.lifespanTextObject.lifespan"
              type="number"
              placeholder="请输入有效期天数"
            />
          </el-form-item>
        </el-row>
        <el-form-item label="发放群体" prop="colony" required>
          <el-select
            v-model="form.colony"
            placeholder="请选择发放群体"
            style="width: 100%"
          >
            <el-option
              v-for="item in [
                { value: 1, label: '新用户' },
                { value: 2, label: '全部用户' },
                { value: 3, label: '指定用户' },
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="指定用户"
          prop="userIds"
          v-if="form.colony == 3"
          required
        >
          <el-select
            v-model="form.userIds"
            multiple
            placeholder="请选择用户"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.userName"
              :value="String(item.id)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用" prop="isDis">
          <el-switch
            v-model="form.isDis"
            active-color="#13ce66"
            :active-value="0"
            :inactive-value="1"
            inactive-color="#999"
          >
          </el-switch>
        </el-form-item>

        <el-form-item label="是否为活动" prop="isActivity">
          <el-switch
            v-model="form.isActivity"
            active-color="#13ce66"
            :active-value="1"
            :inactive-value="0"
            inactive-color="#999"
            @change="handleChangeIsactivity"
          >
          </el-switch>
        </el-form-item>

        <el-form-item v-if="form.isActivity == 1" label="优惠券标签" prop="conpTag" required>
          <el-input v-model="form.conpTag" placeholder="请输入优惠券标签" />
        </el-form-item>

        <el-form-item v-if="form.isActivity == 1" label="优惠券数量" prop="conpNum" required>
          <el-input
            v-model="form.conpNum"
            type="number"
            placeholder="请输入优惠券数量"
          />
        </el-form-item>

        <el-form-item v-if="form.isActivity == 1" label="开始领取时间" prop="grantTime" required>
          <el-date-picker
            v-model="form.grantTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            type="date"
            placeholder="选择开始日期"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item v-if="form.isActivity == 1" label="结束领取时间" prop="stopTime" required>
          <el-date-picker
            v-model="form.stopTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            type="date"
            placeholder="选择结束日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCoupon,
  getCoupon,
  delCoupon,
  addCoupon,
  updateCoupon,
} from "@/api/system/coupon";
import { wxappUser } from "@/api/system/user";
import { listProduct } from "@/api/system/product";
import { listGoodInfo } from "@/api/system/goodInfo";
export default {
  name: "Coupon",
  data() {
    return {
      productList: [],
      tuangouProList: [],
      userList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 优惠券表格数据
      couponList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        icon: null,
        range: null,
        type: null,
        subId: null,
        conpType: null,
        conpText: null,
        lifespanType: null,
        lifespanText: null,
        colony: null,
        userIds: null,
        isDis: null,
        isActivity: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getproList();
    this.getuserList();
    this.getList();
    this.gettuangouList();
  },
  methods: {
    /** 查询家政产品信息列表 */
    getproList() {
      this.loading = true;
      listProduct({
        pageSize: 99999,
      }).then((response) => {
        this.productList = response.rows;
      });
    },
    /** 查询团购商品管理列表 */
    gettuangouList() {
      this.loading = true;
      listGoodInfo({
        pageNum: 1,
        pageSize: 999,
      }).then((response) => {
        this.tuangouProList = response.rows;
        this.loading = false;
      });
    },
    /** 查询客户信息列表 */
    getuserList() {
      this.loading = true;
      wxappUser({
        pageSize: 99999,
      }).then((response) => {
        this.userList = response.rows;
      });
    },
    changeDate(e) {
      console.log(e);
      this.$forceUpdate();
    },
    /** 查询优惠券列表 */
    getList() {
      this.loading = true;
      listCoupon(this.queryParams).then((response) => {
        this.couponList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        icon: null,
        range: null,
        type: null,
        subId: null,
        conpType: null,
        conpText: null,
        conpTextObject: {},
        lifespanTextObject: {},
        lifespanType: null,
        lifespanText: null,
        colony: null,
        userIds: null,
        isDis: 0,
        isActivity: 0,
        useType: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加优惠券";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCoupon(id).then((response) => {
        this.form = response.data;
        this.form.userIds = this.form.userIds
          ? this.form.userIds.split(",")
          : null;
        this.form.subId = this.form.subId ? this.form.subId.split(",") : null;
        this.$set(
          this.form,
          "startTime",
          this.form.lifespanTextObject.startTime
        );
        this.$set(this.form, "endTime", this.form.lifespanTextObject.endTime);
        this.open = true;
        this.title = "修改优惠券";
      });
    },
    changeisDis(row) {
      updateCoupon(row).then((res) => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      });
    },
    handleChangeIsactivity(val) {
      if (val === 0) {
        this.form.conpTag = ''
        this.form.conpNum = ''
        this.form.grantTime = ''
        this.form.stopTime = ''
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        // if(this.form.conpTextObject.deductionAmount>=this.form.conpTextObject.fullAmount){
        // 	this.$message({
        // 		message: '折扣金额不能大于等于满减金额',
        // 		type: 'warning'
        // 	});
        // 	return false
        // }
        if (valid) {
          const { startTime, endTime, userIds, subId } = this.form;
          this.form.lifespanTextObject.startTime = startTime;
          this.form.lifespanTextObject.endTime = endTime;
          this.form.userIds = userIds ? userIds.join(",") : null;
          this.form.subId = subId ? subId.join(",") : null;
          this.form.lifespanText = JSON.stringify(this.form.lifespanTextObject);
          this.form.conpText = JSON.stringify(this.form.conpTextObject);
          if (this.form.id != null) {
            updateCoupon(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCoupon(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除优惠券编号为"' + ids + '"的数据项？')
        .then(function () {
          return delCoupon(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/coupon/export",
        {
          ...this.queryParams,
        },
        `coupon_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
